package com.ubs.training.server.dao.impl.hbm;

import com.ubs.training.server.dao.UBSContactDao;
import com.ubs.training.server.dao.model.UBSContact;
import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: xubuntu
 * Date: 8/27/12
 * Time: 3:54 AM
 * To change this template use File | Settings | File Templates.
 */
@Repository("hbmUbsContactDao")
public class HbmUbsContactDao implements UBSContactDao {

    private SessionFactory factory;

    private HibernateTemplate tpl;

    @Resource(name="sessionFactory")
    public void setFactory(SessionFactory factory) {
        this.factory = factory;
        tpl = new HibernateTemplate(factory);
    }

    public SessionFactory getFactory() {
        return factory;
    }

    @Override
    public List<UBSContact> getAll() {
        return tpl.loadAll(UBSContact.class);
    }

    @Override
    public UBSContact getById(int id) {
        return tpl.load(UBSContact.class, id);
    }

    @Override
    public void add(UBSContact u) {
        tpl.save(u);
    }

    @Override
    public void update(UBSContact u) {
        tpl.merge(u);
    }

    @Override
    public void delete(int id) {
        UBSContact ubs = (UBSContact) factory.getCurrentSession().get(UBSContact.class, id);
        tpl.delete(ubs);
    }

    @Override
    public List<UBSContact> getAllUBSContactByClientId(int id) {
        Criteria criteria = factory.getCurrentSession().createCriteria(UBSContact.class);
        List<UBSContact> list = criteria.list();
        List<UBSContact> result = new ArrayList<UBSContact>();
        for(Iterator it = list.iterator();it.hasNext();){
            UBSContact ubs = (UBSContact)it.next();
            if(ubs.getClient_id() == id){
                result.add(ubs);
            }
        }
        return result;
    }
}
